#!/usr/bin/env python
# -*- coding: utf -*-
# from MLab import *
# from FFT import *
from dislin import *
from numpy import *
import pyaudio
import struct
import sys
import wave
from array import array
from functions import *

CHUNK = int(sys.argv[1])
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

# Input args
window_name = sys.argv[2]   
lin_log = sys.argv[3]

window_size = CHUNK
print "Sampling frequency: " + str(RATE)
print "FFT size: " + str(window_size)
print "Used window: " + str(window_name)
if lin_log == 'log':
    print "Using logarythmic scale: yes"
else:
    print "Using logarythmic scale: no"

n_out_pts = (window_size / 2) + 1
x_axis = linspace(0, RATE / 2, n_out_pts)  # arange(0, RATE / 2, n_out_pts)
gradient_res = 512
moc_K = 0.0
moc_M = 0.0
liczba_M = 0
liczba_K = 0
iteracja = 1
iter_limit = 8
while (True):
    
    # Reading next chunk of input samples
    signal = fromstring(stream.read(CHUNK), dtype=short)
    stream.stop_stream()
    signal = signal
#    if lin_log != 'log':
#        signal = signal / 32768.0
    
    # Window the data plus other possible windows
    if window_name == 'hamming':
            signal = signal * hamming(window_size)
    else:
        if window_name == 'hanning':
            signal = signal * hanning(window_size)
        else: 
            if window_name == 'kaiser':
                signal = signal * kaiser(window_size, 0.5)
    
    # Transform with the FFT, Return Power
    freq_pwr = 2 * abs(fft.rfft(signal, window_size)) / window_size
    max_val = max(freq_pwr)
    freq_pwr[0] = max_val / 100000000.0
    for i in range(1, len(freq_pwr)):
        zakres = (RATE / window_size) * i
        if zakres >= 85.0 and zakres <= 155.0:
            moc_M += freq_pwr[i]
            liczba_M += 1
        else:
            if zakres > 165 and zakres <= 255:
                moc_K += freq_pwr[i]
                liczba_K += 1
            else:
                if(zakres > 325):
                    break
    if iteracja == iter_limit:
        iteracja = 1
        moc_M /= liczba_M
        moc_K /= liczba_K
        print 'Moc_M: ' + str(moc_M)
        print "Moc_K: " + str(moc_K)
        if moc_M > moc_K:
            print "Facet"
        else:
            print "Kobieta"
        moc_K = 0.0
        moc_M = 0.0
        liczba_M = 0
        liczba_K = 0
        iteracja = 0
    if lin_log == 'log':
        freq_pwr = 10 * log10(1e-20 + freq_pwr / max_val)
    plot (x_axis, freq_pwr)
    stream.start_stream()
    iteracja += 1

stream.stop_stream()
stream.close()
p.terminate()
